import os
import random
import re

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from rest_framework.permissions import IsAuthenticated

from mlh.utils.raise_exceptions import MyError

from django.shortcuts import render

# Create your views here.
from rest_framework import mixins
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users import constants
from users.models import User
from users.serializers import UserChangeDetailSerializer, UserDetailSerializer, UserChangeEduExpSerializer, \
    UserAnswerSerializer
from wenda.models import Answer
from users.serializers import UserChangeDetailSerializer, UserDetailSerializer
from wenda.models import Qusetions
from . import serializers
import logging

logger = logging.getLogger('django')


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    """
    短信验证码
    传入参数：
        mobile
    """
    def get(self, request, mobile):
        # 校验手机号,判断是否在60s是否有发送记录
        redis_conn = get_redis_connection('verify')
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise MyError

        # 判断手机号是否被注册
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            raise MyError

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)

        # 保存短信验证码
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 保存发送短信记录
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 发送短信验证码
        # 省略

        return Response({"message": "OK"})


# post http://127.0.0.1:8000/users/
class UserView(CreateAPIView):
    """
    用户注册
    传入参数：
        username, password, sms_code, mobile, allow
    """
    serializer_class = serializers.CreateUserSerializer


# POST /authorizations/
class AuthorizationsView(GenericAPIView):
    """用户登陆"""
    serializer_class = serializers.CheckUserSerializer

    def post(self, request):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # a = re.search(r'/avatar_image.*', serializer.data['avatar'])
        # print(a.group())
        # print('------------------')
        # # print(serializer.data['avatar'])
        # serializer.data['avatar'] = a.group()
        # print(serializer.data['avatar'])

        return Response(serializer.data)


# GET userdetail/2/
class UserDetailAPIView(RetrieveAPIView):

    """用户详情页"""
    # permission_classes = [IsAuthenticated]
    serializer_class = serializers.UserDetailSerializer
    # queryset = User.objects.all()

    # def get(self):
    #     # 获取用户ｉｄ
    #     # 验证用户是否存在
    #     # 序列化返回数据

    def get_object(self):
        user_id = self.kwargs['user_id']
        # print("显示用户%s的详情页面" % user_id)
        return User.objects.get(id=user_id)


# PATCH userdetails/pk/
class UserChangeDetailAPIView(UpdateAPIView):
    """个人档案修改"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer
    queryset = User.objects.all()


class UserChangeEduExpAPIView(UpdateAPIView):
    """用户教育&经历"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserChangeEduExpSerializer
    queryset = User.objects.all()


# POST userdetail/pk/
# class UserChangeDetailAPIView(GenericAPIView):
#     """个人档案修改"""
#     # permission_classes = [IsAuthenticated]
#     serializer_class = UserDetailSerializer
#
#     def post(self, request, pk):
#         user = User.objects.get(id=pk)
#         serializer = self.get_serializer(user, data=request.data, partial=True)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data)


# post user/avatar/
class UserAvatarAPIView(APIView):
    """头像保存"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        image = request.data.get('image')
        user_id = request.data.get('user_id')
        # path = default_storage.save('mlh/media/avatar/' + image, ContentFile(image.name.read()))
        # file = os.path.join(settings.MEDIA_ROOT, path)
        # return Response({"message": "OK"})
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            logging.error("用户不存在")
            return Response({"message": "图片上传失败"})

        path = os.path.join(settings.MEDIA_ROOT, 'avatar_image', image.name)

        with open(path, 'wb') as pic:
            for p in image.chunks():
                pic.write(p)

        user.avatar = 'avatar_image/%s' % image.name
        user.save()

        return Response({"message": "OK"})


class UserInfoView(RetrieveAPIView):
    """
    个人账号详情页
    """
    serializer_class = serializers.UserInfoSerializer

    def get_object(self):
        user_id = self.kwargs['user_id']
        return User.objects.get(id=user_id)


class UserInfoUpdateView(UpdateAPIView):

    serializer_class = serializers.UserInfoSerializer
    queryset = User.objects.all()


# GET /user/answers
class UserAnswer(ListAPIView):
    """用户回答的问题"""

    # 返回用户回答的问题(五条数据，按照时间倒序排序)
    # 数据格式 [{"title": 问题的标题, "like_count": 问题点赞的数量, "update_time": 用户回答问题的时间}, {}, {}]

    # 查询用户所有回答的问题 answer = Answer.objects.get(respondent_id=user_id)  查询字符串形式获取用户id

    # 序列化返回
    serializer_class = UserAnswerSerializer

    # def get_queryset(self):
    #     user = self.request.user
    #     return Answer.objects.get(respondent=user)

    def get_queryset(self):
        user_id = self.kwargs['pk']
        return Answer.objects.filter(respondent_id=user_id)[0:5]





class UserMyquestionView(ListAPIView):
    """
    我的提问
    """

    serializer_class = serializers.UserMyquestserializer

    def get_queryset(self):
        user_id = self.kwargs.get('user_id')
        # print("我卢本伟是真的牛逼   ——————————%s" %user_id)
        return Qusetions.objects.filter(author=user_id)


